import React, { useState, useEffect } from 'react';
import { aiInquiryApi } from '../services/api';

interface AiInquiry {
  id: number;
  inquiryNo: string;
  customerName: string;
  customerPhone: string;
  totalAmount: number;
  status: 'pending' | 'processing' | 'completed' | 'cancelled';
  createTime: string;
  products: Array<{
    name: string;
    quantity: number;
    estimatedPrice: number;
  }>;
  aiResponse?: string;
  adminResponse?: string;
}

const AiInquiryList: React.FC = () => {
  const [inquiries, setInquiries] = useState<AiInquiry[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectedStatus, setSelectedStatus] = useState('all');
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedInquiry, setSelectedInquiry] = useState<AiInquiry | null>(null);
  const [showResponseModal, setShowResponseModal] = useState(false);
  const [responseText, setResponseText] = useState('');

  const statusMap = {
    pending: { label: '待处理', color: '#fa8c16', background: '#fff7e6' },
    processing: { label: '处理中', color: '#1890ff', background: '#f0f5ff' },
    replied: { label: '已回复', color: '#722ed1', background: '#f9f0ff' },
    completed: { label: '已完成', color: '#52c41a', background: '#f6ffed' },
    cancelled: { label: '已取消', color: '#ff4d4f', background: '#fff2f0' }
  };

  useEffect(() => {
    // 调用API获取AI咨询列表
    const fetchAiInquiries = async () => {
      try {
        const response: any = await aiInquiryApi.getAiInquiries(currentPage, pageSize, selectedStatus);
        if (response.isSuccess && response.data) {
          setInquiries(response.data);
          setTotal(response.total || 0);
        }
      } catch (error) {
        console.error('获取AI咨询列表失败:', error);
        alert('获取AI咨询列表失败');
      }
    };
    fetchAiInquiries();
  }, [currentPage, pageSize, selectedStatus]);

  const handleViewDetail = (inquiry: AiInquiry) => {
    setSelectedInquiry(inquiry);
    setShowDetailModal(true);
  };

  const handleStatusChange = async (inquiryId: number, newStatus: AiInquiry['status']) => {
    try {
      await aiInquiryApi.updateAiInquiryStatus(inquiryId, newStatus);
      // 重新获取AI咨询列表
      const response: any = await aiInquiryApi.getAiInquiries(currentPage, pageSize, selectedStatus);
      if (response.isSuccess && response.data) {
        setInquiries(response.data);
        setTotal(response.total || 0);
      }
      alert('状态更新成功');
    } catch (error) {
      console.error('状态更新失败:', error);
      alert('状态更新失败');
    }
  };

  const handleResponse = (inquiry: AiInquiry) => {
    setSelectedInquiry(inquiry);
    setResponseText(inquiry.adminResponse || '');
    setShowResponseModal(true);
  };

  const handleSubmitResponse = async () => {
    if (!responseText.trim()) {
      alert('请输入回复内容');
      return;
    }

    if (selectedInquiry) {
      try {
        await aiInquiryApi.replyAiInquiry(selectedInquiry.id, responseText);
        // 重新获取AI咨询列表
        const response: any = await aiInquiryApi.getAiInquiries(currentPage, pageSize, selectedStatus);
        if (response.isSuccess && response.data) {
          setInquiries(response.data);
          setTotal(response.total || 0);
        }
        alert('回复成功');
        setShowResponseModal(false);
      } catch (error) {
        console.error('回复失败:', error);
        alert('回复失败');
      }
    }
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2>AI咨询管理</h2>
        <div style={{ display: 'flex', gap: 8 }}>
          <span style={{ lineHeight: '32px' }}>今日咨询：</span>
          <span style={{ fontSize: 18, fontWeight: 'bold', color: '#1890ff' }}>8</span>
        </div>
      </div>

      {/* 筛选区域 */}
      <div style={{ marginBottom: 16, padding: '16px', background: 'white', borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span>状态筛选：</span>
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}
          >
            <option value="all">全部状态</option>
            {Object.entries(statusMap).map(([key, value]) => (
              <option key={key} value={key}>{value.label}</option>
            ))}
          </select>
        </div>
      </div>

      {/* 咨询列表 */}
      <div style={{ background: 'white', borderRadius: 8, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#fafafa' }}>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>咨询编号</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>客户信息</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>商品信息</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>预估金额</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>咨询状态</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>创建时间</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {inquiries.map(inquiry => (
              <tr key={inquiry.id} style={{ borderBottom: '1px solid #f0f0f0' }}>
                <td style={{ padding: 12, fontWeight: 'bold' }}>{inquiry.inquiryNo}</td>
                <td style={{ padding: 12 }}>
                  <div>{inquiry.customerName}</div>
                  <div style={{ color: '#666', fontSize: 12 }}>{inquiry.customerPhone}</div>
                </td>
                <td style={{ padding: 12 }}>
                  <div style={{ maxWidth: 200 }}>
                    {inquiry.products.map((product, index) => (
                      <div key={index} style={{ fontSize: 12, marginBottom: 4 }}>
                        {product.name} × {product.quantity}
                      </div>
                    ))}
                  </div>
                </td>
                <td style={{ padding: 12 }}>
                  <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>¥{inquiry.totalAmount}</span>
                </td>
                <td style={{ padding: 12 }}>
                  <span style={{ 
                    padding: '4px 8px', 
                    borderRadius: 4, 
                    fontSize: 12,
                    background: statusMap[inquiry.status]?.background || '#f5f5f5',
                    color: statusMap[inquiry.status]?.color || '#666'
                  }}>
                    {statusMap[inquiry.status]?.label || inquiry.status}
                  </span>
                </td>
                <td style={{ padding: 12 }}>{inquiry.createTime}</td>
                <td style={{ padding: 12 }}>
                  <button 
                    onClick={() => handleViewDetail(inquiry)}
                    style={{ marginRight: 8, padding: '4px 8px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                  >
                    查看详情
                  </button>
                  {inquiry.status === 'pending' && (
                    <button 
                      onClick={() => handleResponse(inquiry)}
                      style={{ marginRight: 8, padding: '4px 8px', background: '#52c41a', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                    >
                      回复
                    </button>
                  )}
                  {inquiry.status === 'processing' && (
                    <button 
                      onClick={() => handleStatusChange(inquiry.id, 'completed')}
                      style={{ marginRight: 8, padding: '4px 8px', background: '#52c41a', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                    >
                      完成
                    </button>
                  )}
                  {inquiry.status === 'pending' && (
                    <button 
                      onClick={() => handleStatusChange(inquiry.id, 'cancelled')}
                      style={{ padding: '4px 8px', background: '#ff4d4f', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                    >
                      取消
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button 
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === 1 ? '#f5f5f5' : '#1890ff', 
              color: currentPage === 1 ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === 1 ? 'not-allowed' : 'pointer' 
            }}
          >
            上一页
          </button>
          <span style={{ padding: '8px 12px' }}>
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          <button 
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === totalPages ? '#f5f5f5' : '#1890ff', 
              color: currentPage === totalPages ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === totalPages ? 'not-allowed' : 'pointer' 
            }}
          >
            下一页
          </button>
        </div>
      </div>

      {/* 咨询详情模态框 */}
      {showDetailModal && selectedInquiry && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: 'white',
            padding: 24,
            borderRadius: 8,
            width: 600,
            maxWidth: '90vw',
            maxHeight: '90vh',
            overflowY: 'auto'
          }}>
            <h3 style={{ marginTop: 0, marginBottom: 24 }}>
              AI咨询详情 - {selectedInquiry.inquiryNo}
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
              <div>
                <h4 style={{ marginBottom: 8 }}>客户信息</h4>
                <div style={{ padding: 12, background: '#f5f5f5', borderRadius: 4 }}>
                  <div>姓名：{selectedInquiry.customerName}</div>
                  <div>电话：{selectedInquiry.customerPhone}</div>
                </div>
              </div>
              <div>
                <h4 style={{ marginBottom: 8 }}>咨询信息</h4>
                <div style={{ padding: 12, background: '#f5f5f5', borderRadius: 4 }}>
                  <div>咨询编号：{selectedInquiry.inquiryNo}</div>
                  <div>创建时间：{selectedInquiry.createTime}</div>
                  <div>咨询状态：
                    <span style={{ 
                      padding: '2px 6px', 
                      borderRadius: 2, 
                      fontSize: 12,
                      background: statusMap[selectedInquiry.status]?.background || '#f5f5f5',
                      color: statusMap[selectedInquiry.status]?.color || '#666',
                      marginLeft: 8
                    }}>
                      {statusMap[selectedInquiry.status]?.label || selectedInquiry.status}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div style={{ marginBottom: 24 }}>
              <h4 style={{ marginBottom: 8 }}>商品信息</h4>
              <div style={{ background: '#f5f5f5', borderRadius: 4, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: '#e8e8e8' }}>
                      <th style={{ padding: 8, textAlign: 'left' }}>商品名称</th>
                      <th style={{ padding: 8, textAlign: 'center' }}>数量</th>
                      <th style={{ padding: 8, textAlign: 'right' }}>预估价格</th>
                      <th style={{ padding: 8, textAlign: 'right' }}>小计</th>
                    </tr>
                  </thead>
                  <tbody>
                    {selectedInquiry.products.map((product, index) => (
                      <tr key={index}>
                        <td style={{ padding: 8 }}>{product.name}</td>
                        <td style={{ padding: 8, textAlign: 'center' }}>{product.quantity}</td>
                        <td style={{ padding: 8, textAlign: 'right' }}>¥{product.estimatedPrice}</td>
                        <td style={{ padding: 8, textAlign: 'right' }}>¥{product.estimatedPrice * product.quantity}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div style={{ padding: 16, textAlign: 'right', background: '#f0f0f0' }}>
                <span style={{ fontSize: 18, fontWeight: 'bold', color: '#ff4d4f' }}>
                  总计：¥{selectedInquiry.totalAmount}
                </span>
              </div>
            </div>
            {selectedInquiry.aiResponse && (
              <div style={{ marginBottom: 16 }}>
                <h4 style={{ marginBottom: 8 }}>AI识别结果</h4>
                <div style={{ padding: 12, background: '#f0f5ff', borderRadius: 4, border: '1px solid #adc6ff' }}>
                  {selectedInquiry.aiResponse}
                </div>
              </div>
            )}
            {selectedInquiry.adminResponse && (
              <div style={{ marginBottom: 24 }}>
                <h4 style={{ marginBottom: 8 }}>管理员回复</h4>
                <div style={{ padding: 12, background: '#f6ffed', borderRadius: 4, border: '1px solid #b7eb8f' }}>
                  {selectedInquiry.adminResponse}
                </div>
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 24 }}>
              <button
                onClick={() => setShowDetailModal(false)}
                style={{ padding: '8px 16px', background: '#f0f0f0', border: '1px solid #d9d9d9', borderRadius: 4, cursor: 'pointer' }}
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 回复模态框 */}
      {showResponseModal && selectedInquiry && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: 'white',
            padding: 24,
            borderRadius: 8,
            width: 500,
            maxWidth: '90vw'
          }}>
            <h3 style={{ marginTop: 0, marginBottom: 24 }}>
              回复咨询 - {selectedInquiry.inquiryNo}
            </h3>
            <div style={{ marginBottom: 24 }}>
              <label style={{ display: 'block', marginBottom: 8 }}>回复内容：</label>
              <textarea
                value={responseText}
                onChange={(e) => setResponseText(e.target.value)}
                style={{ 
                  width: '100%', 
                  height: 120, 
                  padding: 8, 
                  border: '1px solid #d9d9d9', 
                  borderRadius: 4,
                  resize: 'vertical'
                }}
                placeholder="请输入回复内容..."
              />
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
              <button
                onClick={() => setShowResponseModal(false)}
                style={{ padding: '8px 16px', background: '#f0f0f0', border: '1px solid #d9d9d9', borderRadius: 4, cursor: 'pointer' }}
              >
                取消
              </button>
              <button
                onClick={handleSubmitResponse}
                style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer' }}
              >
                发送回复
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AiInquiryList; 